import {useState, useEffect, useCallback} from 'react';
import { useParams} from 'react-router-dom';

import classes from './Comments.module.css';
import NewCommentForm from './NewCommentForm';
import useHttp from "../../hooks/use-http";
import { getAllComments } from "../../lib/api";
import LoadingSpinner from "../UI/LoadingSpinner";
import CommentsList from "./CommentsList";

const Comments = () => {
  const [isAddingComment, setIsAddingComment] = useState(false);

  const params = useParams();

  const {quoteId } = params;

  const { sendRequest, status, data: loadedComments} = useHttp(getAllComments);

  useEffect(() => {
      sendRequest(quoteId);
  },[sendRequest,quoteId]);
  const startAddCommentHandler = () => {
    setIsAddingComment(true);
  };

  const addedCommentHandler = useCallback(() => {
    sendRequest(quoteId);
  },[sendRequest, quoteId]);

  let comments;

  if (status === 'pending') {
      comments =  <div className="centered">
          <LoadingSpinner />
      </div>
  }

  if (status === 'completed' && (loadedComments && loadedComments.length > 0)) {
      comments=  <CommentsList comments={loadedComments} />
  }

  if (status === 'completed' && (!loadedComments || loadedComments.length === 0)){
      comments = <p className="centered">暂时还没有评论!</p>
  }

  return (
    <section className={classes.comments}>
      <h2>用户评论</h2>
      {!isAddingComment && (
        <button className='btn' onClick={startAddCommentHandler}>
          添加新评论
        </button>
      )}
      {isAddingComment && <NewCommentForm
          quoteId={params.quoteId}
          onAddedComment={addedCommentHandler} />}
      <div>{comments}</div>
    </section>
  );
};

export default Comments;
